import os
import cgi

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

import auth
import datastore

# Request handlers


class MainPage(webapp.RequestHandler):
    def get(self):
	# Authorize users from datastore list of allowed emails
        template_values = {}
        if auth.request_authorize(self, template_values, '/') == False:
            return

        # Page specific code

        user = users.get_current_user() # this always returns something cuz we authorize only non-anonymous

        nickname = user.nickname()
        email = user.email()
        greeting = 'Hi there, ' + nickname + ':) '

        template_values['greeting'] = greeting


        mytrees_query = datastore.Webtree.gql('WHERE owner = :1 ORDER BY name', users.get_current_user())
        mytrees = mytrees_query.fetch(64)
        template_values['mytrees'] = mytrees
        
        pubtrees_query = datastore.Webtree.gql('WHERE public = True ORDER BY name')
        pubtrees = pubtrees_query.fetch(128)
        template_values['pubtrees'] = pubtrees
        
        anontrees_query = datastore.Webtree.gql('WHERE anonymous = True ORDER BY name')
        anontrees = anontrees_query.fetch(256)
        template_values['anontrees'] = anontrees
        

        # Generate html from django template.
        auth.request_generate(self,'templates/main.html',template_values)


# Url switching table

application = webapp.WSGIApplication([
        ('/', MainPage),
        ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
